package cn.zzp.org.service.impl;

import cn.zzp.basic.service.impl.BaseServiceImpl;
import cn.zzp.basic.util.PageList;
import cn.zzp.org.domain.Department;
import cn.zzp.org.mapper.DepartmentMapper;
import cn.zzp.org.query.DepartmentQuery;
import cn.zzp.org.service.DepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.xmlunit.diff.ElementSelector;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName DepartmentServiceImpl
 * @Description
 * @Author 祝志鹏
 * @Date 2022/7/14 14:16
 */
@Service
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;



    /**
     * 添加部门
     * @param department
     */
    @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.add(department);

        update(department);
    }

    /**
     * 修改部门
     * @param department
     */
    @Transactional
    @Override
    public void update(Department department) {

        Long parent_id = department.getParent_id();
        if (parent_id == null) {
            department.setDirPath("/"+department.getId());
        }else {
            Department parent = departmentMapper.queryById(parent_id);
            department.setDirPath(parent.getDirPath()+"/"+department.getId());
        }

        departmentMapper.update(department);
    }




    /**
     * 上级部门树
     * @return
     */
    @Override
    public List<Department> deptTree() {

        // 1. 查询所有
        List<Department> all = departmentMapper.queryAll();
        // 2. 准备map
        HashMap<Long, Department> map = new HashMap<>();

        // 3. 遍历所有对象，存入map
        for (Department department : all) {
            map.put(department.getId(), department);
        }

        // 4. 准备返回前端数据集合
        List<Department> deptTree = new ArrayList<>();

        for (Department department : all) {
            // 判断是否是顶级部门
            // 如果是，直接添加
            if (department.getParent_id() == null){
                deptTree.add(department);
            }else { // 如果不是，找出父级部门，然后再存入父级部门的子集
                Long parent_id = department.getParent_id();
                // 通过id找出父级对象
                Department parent = map.get(parent_id);
                // 存入父级部门子集
                parent.getChildren().add(department);
            }
        }

        return deptTree;
    }
}
